<template>
  <div>
    <van-search
      v-model="word"
      show-action
      label="商品"
      background="greenyellow"
      placeholder="请输入搜索关键词"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <h5 style="font-size: 16px">历史记录</h5>
    <div class="histories">
      <div class="his" @click="clickHis(his)" v-for="his in hises" :key="his">
        {{ his }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      word: "",
      hises: localStorage.getItem("his")
        ? JSON.parse(localStorage.getItem("his"))
        : [],
    };
  },
  methods: {
    clickHis(word){
      // 点击历史记录进行搜索
      this.word=word
      this.onSearch()
    },
    onSearch() {
      // 跳转到 搜索的结果页，并将搜索的关键字传入
      // 重新获取缓存，转换成数组，先数组插入数据 再存回去
      let his = localStorage.getItem("his")
        ? JSON.parse(localStorage.getItem("his"))
        : [];
      his.unshift(this.word);
      // 控制长度
      his.length = 5;
      his = [...new Set(his)]
      localStorage.setItem("his", JSON.stringify(his));
      this.$router.push({
        path: "/searchList",
        query: {
          word: this.word,
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.van-search__content {
  border-radius: 15px;
}
.histories {
  display: flex;
  flex-wrap: wrap;
  .his {
    line-height: 30px;
    font-size: 14px;
    color: #666;
    margin: 0 10px;
  }
}
</style>